from __future__ import print_function
import hmac
import hashlib
import time
import magic
import logging

def hmacSHA256(key, message):
    return hmac.new(key, message, hashlib.sha256).hexdigest()
    
def humanSize(bytes, precision=1):
    abbrevs = (
        (1<<50L, 'PB'),
        (1<<40L, 'TB'),
        (1<<30L, 'GB'),
        (1<<20L, 'MB'),
        (1<<10L, 'kB'),
        (1, 'bytes')
    )
    if bytes == 1:
        return '1 byte'
    for factor, suffix in abbrevs:
        if bytes >= factor:
            break
    #return '%.*f %s' % (precision, bytes / factor, suffix)
    #return "{:03.2f} {}".format  (precision, bytes / factor, suffix)
    return "{:.2f} {}".format  (float(bytes / factor), suffix)

def timeSinceEpoch(seconds):
	return time.strftime("%c", time.localtime(seconds))

def calcPercent(numerator, denominator, precision = 2):
        return round((float(numerator) / float(denominator,)) * 100, precision)

def printPercentComplete(bytesXmited, bytesToXmit):
        print("{} / {} ({}%)     \r".format(humanSize(bytesXmited), humanSize(bytesToXmit), calcPercent(bytesXmited, bytesToXmit)), end='')

def printSimplePercentComplete(completed, total):
        print("{} / {} ({}%)     \r".format(completed, total, calcPercent(completed, total)), end='')

def sha256HashFile(filename):
	m = hashlib.sha256()
	with open(filename, "r") as fp:
		while True:
			data = fp.read(2**20)
			if not data:
				break
			m.update(data)
	return m.hexdigest()	

def fileMime(fqpn):
	try:
		return magic.from_file(fqpn, mime=True)
	except:
		raise

def getFqpnFromMediaObject(pdriveFiles, mediaObj):
	hmac = hmacSHA256(str(mediaObj["filesize"]), mediaObj["sha256Hash"])
	hashbyte = hmac[0]
	return "{}/{}/{}.{}".format(pdriveFiles, hashbyte, hmac, mediaObj["fileType"])

def getRelativeMediaFile(mediaObj):
	hmac = hmacSHA256(str(mediaObj["filesize"]), mediaObj["sha256Hash"])
	hashbyte = hmac[0]
	return "{}/{}.{}".format(hashbyte, hmac, mediaObj["fileType"])
    
def getRelativeMediaWebFile(mediaObj):
    hmac = hmacSHA256(str(mediaObj["webPicFileSize"]), mediaObj["webPicSha256Hash"])
    hashbyte = hmac[0]
    return "{}/{}.{}".format(hashbyte, hmac, "png")


def getFqpnFromData(pdriveFiles, filesize, sha256Hash, fileType):
	hmac = hmacSHA256(str(filesize), sha256Hash)
	hashbyte = hmac[0]
	return "{}/{}/{}.{}".format(pdriveFiles, hashbyte, hmac, fileType)

def getSecureDownloadKey(relpath, secureDownloadKey):
	if relpath[0] != "/":
		relpath = "/" + relpath
	hextime = "%08x" % time.time()
	token = hashlib.md5(secureDownloadKey + relpath + hextime).hexdigest()
	return "{}/{}{}".format(token, hextime, relpath)
